// 对象拼接成:a=1&b=2字符串
export function changeObj(obj) {
    let ary = [];
    for (let p in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, p)) {
            ary.push(encodeURIComponent(':' + p) + '=' + encodeURIComponent(obj[p]));
        }
    }
    return ary.join('&');
}

// 对象拼接成:a=1&b=2字符串
export function changeObjStr(obj) {
    let ary = [];
    for (let p in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, p)) {
            ary.push(encodeURIComponent('' + p) + '=' + encodeURIComponent(obj[p]));
        }
    }
    return ary.join('&');
}


/** 传入一个数组,依据分隔段数计算最大值,最小值,段间隔**/
export function calYNum(arr, splitNumber = 5) {
    let rData = {
            RMax: 0,
            RMin: 0,
            interval: 0
        },
        max = Math.max.apply(null, arr),
        min = Math.min.apply(null, arr);
    if (max === 0 && max === min) {
        rData = {
            RMax: 1,
            RMin: 0,
            interval: 0.2
        };
        return rData;
    }
    // 如果为率值都为100时
    if (max === 100 && max === min) {
        rData = {
            RMax: 100,
            RMin: 99,
            interval: 0.2
        };
        return rData;
    }
    let interval = (max - min) / splitNumber;
    max = Math.ceil(max + interval);
    rData.RMax = max;
    if (min >= 0) {
        min = min === 0 ? min : Math.floor(min - interval) < 0 ? 0 : Math.floor(min - interval);
    } else {
        min = min === 0 ? min : Math.floor(min - interval);
    }
    if (max === min) {
        min = 0;
    }
    rData.RMin = min;
    interval = (max - min) / splitNumber;
    rData.interval = interval;
    return rData;
}

// 数组单位转换，数组元素是对象
export function changeArrObjUnit(unit = '', ...arrAccept) {
    let max = 0,
        type = '01', // 01 小于1万,02大于1亿，03大于1万小于1亿
        allArr = [],
        arr = deepClone(arrAccept);
    arr[0].forEach(item => {
        allArr.push(Number(item.value));
    });
    allArr.forEach(item => {
        if (parseFloat(String(Math.abs(item))) > max) { max = item; }
    });
    if (String(max).split('.')[0].length >= 9) {
        // 转换亿单位
        type = '02';
        unit = '亿' + unit;
    } else if (String(max).split('.')[0].length >= 5) {
        // 转换万单位
        type = '03';
        unit = '万' + unit;
    }

    let dealItem = (item, fenmu) => {
        if (fenmu) {
            item = (parseFloat(item) / fenmu).toFixed(2).split('.')[1] === 0 ? (parseFloat(item) / fenmu).toFixed(0) : (parseFloat(item) / fenmu).toFixed(2);
        } else {
            item =
                parseFloat(item)
                    .toFixed(2)
                    .split('.')[1] === 0 ?
                    parseFloat(item).toFixed(0) :
                    parseFloat(item).toFixed(2);
        }
        return item;
    };

    if (type === '01') {
        arr.forEach(arrItem => {
            arrItem.forEach((item, index) => {
                arrItem[index].value = dealItem(Number(item.value));
            });
        });
    } else if (type === '02') {
        arr.forEach(arrItem => {
            arrItem.forEach((item, index) => {
                arrItem[index].value = dealItem(Number(item.value), 100000000);
            });
        });
    } else if (type === '03') {
        arr.forEach(arrItem => {
            arrItem.forEach((item, index) => {
                arrItem[index].value = dealItem(Number(item.value), 10000);
            });
        });
    }
    return {
        unit: unit,
        arr: arr
    };
}

// 千位符号计算规则
export function formartNumberRgx(num) {
    let parts = num.toString().split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    if (parts.length === 1) {
        return parts[0];
    } else {
        return parts[0] + '.' + parts[1];
    }
}

// 单位转换，亿，万，保留两位小数
export function changeUnit(value = '0', unit = '') {
    let returnObj = {
        value: '',
        unit: ''
    };
    value = String(value);
    if (value.split('.')[0].length >= 9) {
        // 转换亿单位
        value = (parseFloat(value) / 100000000).toFixed(2);
        unit = '亿' + unit;
    } else if (value.split('.')[0].length >= 5) {
        // 转换万单位
        value = (parseFloat(value) / 10000).toFixed(2);
        unit = '万' + unit;
    } else if (value.split('.').length > 1) {
        // 携带小数点
        value = parseFloat(value).toFixed(2);
    }
    returnObj.value = value;
    returnObj.unit = unit;
    return returnObj;
}
export function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'shallowClone');
    }
    const targetObj = source.constructor === Array ? [] : {};
    Object.keys(source).forEach(keys => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = source[keys].constructor === Array ? [] : {};
            targetObj[keys] = deepClone(source[keys]);
        } else {
            targetObj[keys] = source[keys];
        }
    });
    return targetObj;
}
// 数组单位转换
export function changeArrUnit(unit = '', ...arrAccept) {
    let max = 0,
        type = '01', // 01 小于1万,02大于1亿，03大于1万小于1亿
        level = 1, // 1 小于1万， 1e4 大于1万小于1亿，1e8 大于1亿
        allArr = [],
        arr = deepClone(arrAccept);
    arr.forEach(item => {
        allArr = [...allArr, ...item];
    });
    allArr.forEach(item => {
        if (parseFloat(String(Math.abs(item))) > max) { max = item; }
    });
    if (String(max).split('.')[0].length >= 9) {
        // 转换亿单位
        type = '02';
        unit = '亿' + unit;
        level = 1e8;
    } else if (String(max).split('.')[0].length >= 5) {
        // 转换万单位
        type = '03';
        unit = '万' + unit;
        level = 1e4;
    }

    let dealItem = (item, fenmu) => {
        if (fenmu) {
            item = (parseFloat(item) / fenmu).toFixed(2).split('.')[1] === 0 ? (parseFloat(item) / fenmu).toFixed(0) : (parseFloat(item) / fenmu).toFixed(2);
        } else {
            item =
                parseFloat(item)
                    .toFixed(2)
                    .split('.')[1] === 0 ?
                    parseFloat(item).toFixed(0) :
                    parseFloat(item).toFixed(2);
        }
        return item;
    };

    if (type === '01') {
        arr.forEach(arrItem => {
            arrItem.forEach((item, index) => {
                arrItem[index] = dealItem(item);
            });
        });
    } else if (type === '02') {
        arr.forEach(arrItem => {
            arrItem.forEach((item, index) => {
                arrItem[index] = dealItem(item, 100000000);
            });
        });
    } else if (type === '03') {
        arr.forEach(arrItem => {
            arrItem.forEach((item, index) => {
                arrItem[index] = dealItem(item, 10000);
            });
        });
    }
    return {
        unit: unit,
        arr: arr,
        level
    };
}

// 52000 to 5.2万，108600000 to 1.09 亿
export const changeNumLevel = num => {
    if (num >= 1e8) {
        return (Math.round(num / 1e6) / 100).toFixed(2) + '亿';
    } else if (num >= 1e4) {
        return (Math.round(num / 100) / 100).toFixed(2) + '万';
    } else {
        return num;
    }
};
// 防抖函数
export function debounce(func, delay) {
    // 维护一个 timer
    let timer = null;
    return function () {
        clearTimeout(timer);
        const context = this,
            args = arguments;
        timer = setTimeout(function () {
            func.apply(context, args);
        }, delay);
    };
}
// 节流
export const throttle = (function () {
    let timer = null;
    let flag = true;
    return function (func, delay = 500) {
        if (flag) {
            flag = false;
            func.call();
            return;
        }
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            flag = true;
            func.call();
        }, delay);
    };
})();

// 根据表头计算表格列宽
export function calcColWidth(colName) {
    if (colName === '序号') {
        return 80;
    } else if (colName.indexOf('时间') > -1 || colName.indexOf('日期') > -1) {
        return 160;
    } else if (colName.indexOf('公司') > -1 || colName.indexOf('单位') > -1) {
        return 230;
    } else if (colName.length < 5) {
        return 160;
    } else if (colName.length >= 6) {
        return 220;
    } else {
        return 180;
    }
}

// 计算详情接口 orgNo 入参格式
export function calcOrgNo(orgNo) {
    let _orgNo = '';
    if (orgNo === '21102') {
        _orgNo = '21%';
    } else if (orgNo.length === 5 && orgNo !== '21102') {
        _orgNo = orgNo + '%';
    } else if (orgNo.length === 7) {
        _orgNo = orgNo;
    }
    return _orgNo;
}
// 数组平分
export function arrAverage(arr, num) {
    let newArr = [];
    for (var i = 0; i < arr.length; i += num) {
        newArr.push(arr.slice(i, i + num));
    }
    return newArr;
}

export function datatoTree(parent, children) {
    parent.map(p => {
        let arr = [];
        children.map((c) => {
            if (c.CODE.indexOf(p.CODE) === 0 && c.CODE.length !== p.CODE.length && c.CODE.length === p.CODE.length + 2) {
                datatoTree([c], children);
                arr.push(c);
            }
        });
        if (arr.length > 0) {
            p.children = arr;
        }
    });
    return parent;
}

export function arrayToTree(initData) {
    let numArr = [];
    initData.map(item => {
        numArr.push(item.CODE.toString().length);
    });
    let minZ = Math.min(...numArr),
        pidArr = {};
    pidArr.value = initData.filter(item => {
        return item.CODE.length === minZ;
    });
    const optionsLx = datatoTree(pidArr.value, initData);
    return optionsLx;
}
// 不四舍五入
export function noRound(v) {
    const num = Math.floor(v * 100) / 100;
    return num
}
export function fontSize(v) {
    return v
}

// 处理async/await异常
export let getAsync = async function (fn) {
    try {
        let resp = await fn;
        return [null, resp];
    } catch (err) {
        return [err, null];
    }
}

/**
* @description 组织机构树，数据处理
* @param {Array} treeList 树数据
* @param {String} type 删除的等级
* @return {void}
*/
export let handleTree = function (treeList, type) {
    treeList.length && treeList.forEach((data) => {
        if (data.children && !data.children.length) {
            delete data.children;
        }
        if (type && data.type === type) {
            delete data.children;
        }

        if (data.children && data.children.length) {
            handleTree(data.children, type);
        }
    });
}